package com.blah.gwtgames.client.mines;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.DOM;
import com.blah.gwtgames.client.common.ui.ProgressBar;

public class MineGame extends Composite implements ChangeListener {
	private Grid grid = new Grid();
	private ProgressBar tileProgress = new ProgressBar();
	private ProgressBar mineProgress = new ProgressBar();
	private Button newGameButton = new Button("New Game");
	private SettingsPanel settings = new SettingsPanel(this);
	
	public MineGame()
	{
		HorizontalPanel hPanel = new HorizontalPanel();
		hPanel.add(tileProgress);
		hPanel.add(mineProgress);
		
		VerticalPanel vPanel = new VerticalPanel();
		vPanel.add(grid);
		vPanel.add(hPanel);
		vPanel.add(newGameButton);
		vPanel.add(settings);
		
		settings.setVisible(false);

		grid.addChangeListener(this);
		newGameButton.addClickListener(
			new ClickListener()
			{
				final SettingsPanel mySettingsDialog = settings;
				final Grid myGrid = grid;

				public void onClick(Widget sender)
				{
					mySettingsDialog.display(
							myGrid.getWidth(),
							myGrid.getHeight(),
							myGrid.getMineCount());
				}
			}
		);

		tileProgress.setWidth("0px");
		mineProgress.setWidth("0px");
		
		update();

		initWidget(vPanel);
	}

	public void onChange(Widget sender) {
		update();
	}

	private void update()
	{
		if (grid.getGameState() == Grid.FINISHED)
		{
			if (grid.getTilesRemaining() == 0)
			{
				tileProgress.setValue(1.0f);
				mineProgress.setValue(1.0f);
			}
			else
			{
				tileProgress.setValue(0.0f);
				mineProgress.setValue(0.0f);
			}
		}
		else
		{
			int totalTiles = grid.getWidth() * grid.getHeight() - grid.getMineCount();
			tileProgress.setValue(1.0f - ((float)grid.getTilesRemaining() / totalTiles));
			
			mineProgress.setValue((float)grid.getFlagCount() / grid.getMineCount());
		}
	}

	public void newGame(int width, int height, int mineCount)
	{
		grid.setSize(width, height, mineCount);
		
		int gridWidth = DOM.getIntAttribute(grid.getElement(), "clientWidth");
		float ratio = (float)mineCount / (width * height);
		
		mineProgress.setWidth((int)(gridWidth * ratio) + "px");
		tileProgress.setWidth((int)(gridWidth * (1 - ratio)) + "px");
	}
}
